import requests
import json
from utils import redis_cach
import ast


def get_deliver(com, nu):
    headers = {"Authorization": "APPCODE {}".format('7285a38ad5e9442b9fa5c1a2ca4a8141')}
    url = "https://ali-deliver.showapi.com/showapi_expInfo"
    params = {
        'nu': nu,
        'com': com,
    }
    result = requests.get(url=url, headers=headers, params=params)

    result_json = json.loads(result.content)
    # print(result_json)
    # 查询失败
    if result_json['showapi_res_code'] != 0:
        return 0, []

    status = result_json['showapi_res_body']['status']
    # print(status)

    # 快递信息
    deliver_info = result_json['showapi_res_body']['data']

    return status, deliver_info


def cache_deliver(simple, num):
    key = '{}_{}'.format(simple, num)
    status_key = '{}_{}_status'.format(simple, num)
    cache_data = redis_cach.get(key)
    if cache_data:
        # print('-------')
        data_to_list = ast.literal_eval(cache_data)
        return data_to_list
    else:
        status, get_data = get_deliver(simple, num)
        # print(get_data)
        if status >= 4:
            redis_cach.set_last(key, str(get_data))
            redis_cach.set_last(status_key, status)
        else:
            redis_cach.sets(key, str(get_data), timeout=1800)
            redis_cach.sets(status_key, status, timeout=1800)
        return get_data


# if __name__ == '__main__':
#     nu = '75360962011068'
#     com = 'zhongtong'
#     data = cache_deliver(com, nu)
#     print(type(data))



